import React, {useEffect, useState} from "react";
import FileApi, {FileObj} from "@/api/web/FileApi.ts";
import {createStyles} from "antd-style";
import {Button, Collapse} from "antd";
import FilePreviewProcess, {ViewConf} from "@/components/FilePreviewProcess";

const useStyles = createStyles(({css, token}) => {
    return {
        container: css`
            font-size: 18px;
            margin: 20px;
        `,
        preview: css`
            
        `,
        header: css`
            font-size: 20px;
            overflow-y: hidden;
            text-align: left;
            color: ${token.colorPrimaryText};
            margin-left: 20px;
            margin-bottom: 20px;
            padding: 5px 0;
        `,
    }
})

interface Props {
    previewFile: FileObj
}


export default ({previewFile}: Props) => {
    const {styles} = useStyles();
    const [viewConfList, setViewConfList] = useState<ViewConf[]>([])
    const [activeKey, setActiveKey] = useState<string[]>([])

    useEffect(() => {
        const _viewConfList = FilePreviewProcess(previewFile);
        setViewConfList(_viewConfList)
        // 如果可预览的项目为1，则自动展开
        if (_viewConfList.length == 1) {
            setActiveKey([_viewConfList[0].key])
        }
    }, [previewFile]);

    return (
        <>
            <h3 className={styles.header}>{previewFile.name}</h3>
            <div className={styles.container}>
                <p>文件类型：{previewFile.type}</p>
                <p>MIME类型：{previewFile.contentType}</p>
            </div>
            <h3 className={styles.header}>文件预览</h3>
            <div className={styles.preview}>
                <Collapse
                    items={viewConfList.map((item) => {
                        return {
                            key: item.key,
                            children: item.fc,
                            label: item.name,
                            styles: {
                                body: {
                                    padding: "0",
                                },
                            },
                        }
                    })}
                    activeKey={activeKey}
                    onChange={(key) => {
                        // 如果 key 是空数组，表示所有面板都关闭；否则设置为当前点击的面板
                        setActiveKey(key.length ? key : []);
                    }}
                />
            </div>
            <Button
                type="link"
                href={FileApi.getFileLink(previewFile.path)}
                target="_blank"
                download
            >下载文件</Button>
        </>
    )
}
